/**
 * 
 */
package org.jim.server.demo.command;

import org.jim.core.ImChannelContext;
import org.jim.core.ImConst;
import org.jim.core.ImPacket;
import org.jim.core.exception.ImException;
import org.jim.core.http.HttpRequest;
import org.jim.core.packets.AuthReqBody;
import org.jim.core.packets.Command;
import org.jim.core.packets.LoginReqBody;
import org.jim.core.utils.JsonKit;
import org.jim.server.JimServerAPI;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.AuthReqHandler;
import org.jim.server.command.handler.LoginReqHandler;
import org.jim.server.processor.handshake.WsHandshakeProcessor;

import ch.qos.logback.core.net.LoginAuthenticator;
/**
 * @author WChao
 *
 */
public class DemoWsHandshakeProcessor extends WsHandshakeProcessor {

	@Override
	public void onAfterHandshake(ImPacket packet, ImChannelContext imChannelContext) throws ImException {
		AuthReqHandler authReqHandler = (AuthReqHandler)CommandManager.getCommand(Command.COMMAND_AUTH_REQ);
		HttpRequest request = (HttpRequest)packet;
		String userId = request.getParams().get("userId") == null ? null : (String)request.getParams().get("userId")[0];
		String appId = request.getParams().get("appId") == null ? null : (String)request.getParams().get("appId")[0];
		String appKey = request.getParams().get("appKey") == null ? null : (String)request.getParams().get("appKey")[0];
		String localId = request.getParams().get("localId") == null ? null : (String)request.getParams().get("localId")[0];
		
		AuthReqBody authReqBody = new AuthReqBody(appId, appKey, null, userId, localId);
		byte[] authBytes = JsonKit.toJsonBytes(authReqBody);
		request.setBody(authBytes);
		try{
			request.setBodyString(new String(authBytes, ImConst.CHARSET));
		}catch (Exception e){
			throw new ImException(e);
		}
		ImPacket authRespPacket = authReqHandler.handler(request, imChannelContext);  
		if(authRespPacket != null){
			JimServerAPI.send(imChannelContext, authRespPacket);
		}
	}
}
